package com.whut.customer.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whut.common.util.R;
import com.whut.customer.entity.UserRoleRelation;
import com.whut.customer.service.IUserRoleRelationService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 用户-角色关联表 前端控制器
 * </p>
 *
 * @author author
 * @since 2021-01-24
 */
@RestController
@RequestMapping("/userRoleRelation")
public class UserRoleRelationController {

    @Autowired
    IUserRoleRelationService userRoleRelationService;

    //授权角色，就是将某一用户和某一角色绑定，写进user_role_relation表中
    @ApiOperation("授权角色")
    @PostMapping("/authorization")
    public R authorization(@RequestBody UserRoleRelation userRoleRelation) {
        if(userRoleRelation.getUserId()==null || userRoleRelation.getRoleId()==null)
            return R.failed("用户id或者角色id不能为空!");

        LambdaQueryWrapper<UserRoleRelation> eq = new LambdaQueryWrapper<UserRoleRelation>()
                .eq(UserRoleRelation::getUserId, userRoleRelation.getUserId())
                .eq(UserRoleRelation::getRoleId, userRoleRelation.getRoleId());
        if (userRoleRelationService.getOne(eq) != null)
            return R.failed("该授权已存在!");

        return R.ok(userRoleRelationService.save(userRoleRelation));
    }

    @ApiOperation("查询用户授权")
    @PostMapping("/getAuthorization")
    public R<List<UserRoleRelation>> getAuthorization(@RequestBody UserRoleRelation userRoleRelation) {
        LambdaQueryWrapper<UserRoleRelation> eq = new LambdaQueryWrapper<UserRoleRelation>()
                .eq(userRoleRelation.getId() != null, UserRoleRelation::getId, userRoleRelation.getId())
                .eq(userRoleRelation.getUserId() != null, UserRoleRelation::getUserId, userRoleRelation.getUserId())
                .eq(userRoleRelation.getRoleId() != null, UserRoleRelation::getRoleId, userRoleRelation.getRoleId());
        return R.ok(userRoleRelationService.list(eq));
    }

}
